import {Component} from '@angular/core';
import {FieldType, FieldTypeConfig} from '@ngx-formly/core';
import {FormControl} from "@angular/forms";
import {Observable} from "rxjs";
import {NzCascaderOption} from "ng-zorro-antd/cascader";

@Component({
  selector: 'app-my-select',
  template: `
    <nz-form-item>
      <nz-form-control [nzSpan]="14" nzErrorTip="Please select your gender!" nzRequired>
        <nz-form-label [nzSpan]="5" nzRequired>{{to.label}}</nz-form-label>
        <nz-select [formControl]="formControl">
          <nz-option *ngFor="let option of convert(to.options)" [nzValue]="option.value"
                     [nzLabel]="convertLabel(option.label)"></nz-option>
        </nz-select>
      </nz-form-control>
    </nz-form-item>
  `,
})
export class MySelectComponent extends FieldType<FieldTypeConfig> {
  convert(options: any[] | Observable<any[]> | undefined): NzCascaderOption[] | null {
    if (options instanceof Observable) {
      // 订阅 Observable 并返回结果
      // return options.subscribe(val => val);
      return null;
    } else if (Array.isArray(options)) {
      // 如果 options 是数组，直接返回
      return options;
    } else {
      // 如果 options 是 undefined，返回 null
      return [];
    }
  }

  convertLabel(options: string | undefined): string | number | null {
    if (typeof options === 'string') {
      return options;
    } else if (typeof options === 'undefined') {
      return null;
    } else {
      return Number(options);
    }
  }
}
